package com.yupi.usercenter.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.contant.UserContant;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.model.User;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yupi.usercenter.contant.UserContant.USER_LOGIN_STATE;

/**
* 用户服务实现类
*
* @author Alex
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-06-11 11:33:01
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;



    /**
     * 用户注册功能具体实现
     *
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @param checkPassword 检验密码
     * @return 新用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1.校验userAccount,userPassword,checkPassword是否为空，userAccount,userPassword,checkPassword长度是否满足设计
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() <  4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短小于4位");
        }
        if (userAccount.length() >  4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过长大于4位");
        }
        if (userPassword.length() < 6 || checkPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短小于6位");
        }
        if (planetCode.length() > 11){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户学号过长大于11位");
        }
        if (planetCode.length() < 11){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户学号过短小于11位");
        }
        // 2.账户是否包含特殊字符
        String validPattern = "\\pP|\\pS|\\s+"; // 正则表达式看是否有特殊字符
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号有特殊字符");
        }
        // 3.密码和校验密码是否相同
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码有误");
        }

        // 4.账户不能重复
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            // 说明该账户已被占用
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }

        // 学号不能重复
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            // 说明该账户已被占用
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学号已存在");
        }

        // 5.对密码进行加密
        String encryptPassword = MD5Util.encrypt(userPassword);

        // 6.向数据库插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "数据插入失败");
        }
        // 插入完成返回用户id
        return user.getId();
    }



    /**
     * 用户登录功能具体实现
     *
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param request
     * @return 用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验userAccount,userPassword是否为空，userAccount,userPassword长度是否满足设计
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户或者密码为空");
        }
        if (userAccount.length() <  4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号小于4位");
        }
        if (userPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码小于6位");
        }

        // 2.账户是否包含特殊字符
        String validPattern = "\\pP|\\pS|\\s+"; // 正则表达式看是否有特殊字符
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号包含特殊字符");
        }

        // 3.对密码进行加密
        String encryptPassword = MD5Util.encrypt(userPassword);

        // 4.查询用户是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            // 说明该账户不存在
            log.info("user login failed, userAccount cannot match userPassword!");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号密码不匹配");
        }

        // 5.用户脱敏
        User safetyUser = getSafetyUser(user);

        // 6.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);


        return safetyUser;
    }

    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setUserStatus(0);
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        return safetyUser;
    }

    /**
     * 用户注销
     * @return
     */
    @Override
    public int  userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




